package candidature.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import util.ServerResponse;
import business.bd.BD;
import business.dto.BasicDTO;
import business.dto.CandidatoDTO;
import business.dto.GestioneCandidatoDTO;
import business.view.CandidatoListRenderer;

/**
 * Servlet implementation class GestioneCandidatoServlet
 */
public class GestioneCandidatoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	private Logger logger=LogManager.getLogger(this.getClass());
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GestioneCandidatoServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException{
    	logger.info("BEGIN - GestioneCandidatoServlet");
    	
    	response.setContentType("text/xml");
    	
    	
	    PrintWriter out = response.getWriter();
    	
    	String action = request.getParameter("action");
	    String method = request.getParameter("method");
	    String target = request.getParameter("target");
	    
	    
	    logger.debug("action - "+action);
	    logger.debug("method - "+method);
    	
	    HashMap parameterList = new HashMap();
	    
	   
	    
	    parameterList.put("servletName", this.getServletName());
        parameterList.put("request", request);
        
        parameterList.put("action", action);
        parameterList.put("method", method);
        
        Map parameterMap = request.getParameterMap();
        Set keySet = parameterMap.keySet();
        
        Iterator it = keySet.iterator();
        
        while (it.hasNext())
        {
            String key = (String) it.next();
            String value = (String) request.getParameter(key);
            
            logger.debug("parameter: "+key+", value:"+value);
            parameterList.put(key, value);
            
        }
        
        ResourceBundle rb= ResourceBundle.getBundle("bundle");
        String propertyValue = rb.getString("test1");
        
        logger.debug("recupero stringa da rb:" +propertyValue);
        
        ServerResponse res = new ServerResponse(this.getServletName(), null, "OK");
        String responseCode="KO";
        
        try {
        	 BD businessDelegation = new BD(action+"."+method);
             businessDelegation.setPackageName("business.bl");
             
             res = (ServerResponse) businessDelegation.delegate(parameterList);
		} catch (Exception e) {
			logger.error("errore evocazione business delegation: ", e);
		}
        finally{
        	 ArrayList<BasicDTO> dtos = new ArrayList<BasicDTO>();
             ArrayList resultList = res.getData();

             if (resultList != null){
                 for (int i = 0; i < resultList.size(); i++)
                 {
                     BasicDTO dto = (BasicDTO) resultList.get(i);
                     dtos.add(dto);
                 }
             }
        	
        	
        	  responseCode=res.getResponseCode();
        	  String responseMessage=res.getResponseMessage();
        	  
        	  res = new ServerResponse(this.getServletName(), null, responseCode);
        	  res.setResponseMessage(responseMessage);
             
        	  StringBuilder sb = new StringBuilder();
//        	  sb.append("<Candidati>");
              for (int i = 0; i < dtos.size(); i++)
              {
                  GestioneCandidatoDTO dto = (GestioneCandidatoDTO) dtos.get(i);

//                  if (headerAttributes!=null) {
//                      dto.setHeaderParameters(headerParameters);
//                  }
                  dto.setResourceBundle(rb);
                  dto.setTarget(target);
                  
                  logger.debug(dto.toString());
                  sb.append(dto.toString());
                  
              }
//              sb.append("</Candidati>");
              
              logger.debug(sb);
             
              String relativeWebPath= "/xsl/pannello.xsl";
              String xslPath = getServletContext().getRealPath(relativeWebPath);
//              String xslPath="c:/apache-tomcat-6.0.36/wtpwebapps/gestione_candidature/xsl/"+"candidato.xsl";
              
              
              
              File f=new File(xslPath);
              
              
              logger.debug("xslPath: "+xslPath+" "+f.exists());
              
              if(sb.length()>0){
            	  CandidatoListRenderer clr=new CandidatoListRenderer(sb.toString(),xslPath);
                  
                  sb = new StringBuilder(clr.getHtml());
                  
                  int start=sb.indexOf("<?xml ");
                  int end = sb.indexOf("?>");
                  
                  if (start>-1) {
    				
                	  logger.debug("start "+start);
                      logger.debug("end "+end);
                      
                      sb.replace(start,end+2 , "");
                  
                  }
                  
                
                  
                  logger.debug("---- Pannello "+sb.toString());
                  
//                  res.addData(clr.getHtml());
            	  
                  res.addData(sb.toString());
              }
              
              res.setTarget(target);
              out.print(res);
              out.close();
        }
    	
    	
    	logger.info("END - GestioneCandidatoServlet");
    }
    	
    
    
    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
